<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Profil extends CI_Controller {

    var $_public_view;

    function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->library('image_moo') ;
        $this->load->helper(array('form', 'url','html','string'));
        $this->load->library('session');
        //$this->load->library('system_libs');
        $this->config->load('ojexcom');
        $this->_public_view = $this->config->item('public_view');
    }

    function index() {
        
        $data = array(
            //'detail' => $this->muser->get_user_trip_detail($str_id),
            'page_title' => 'O-JEX',
            'page_content' => 'profil');
       $this->load->view($this->_public_view, $data);
     }

     function edit(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        //cek authorisasi
        if($id != $str_id){
            echo 'Maaf, Anda tidak bisa mengakses halaman ini';
            redirect('home','refresh');
        }

        $data = array(
            //'detail' => $this->muser->get_user_trip_detail($str_id),
            'output' => $this->get($str_id,$id),
            'page_title' => 'Update Profil',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'update_profil');
       $this->load->view($this->_public_view, $data);
    }

     function detail($isUpdate=''){
        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        
        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        if($this->session->userdata('page') and $isLogin){
            $this->session->unset_userdata('page');
        } else {
            $this->session->set_userdata('page','profil/detail/'.$str_id);
        }
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        } else {
            echo "silakan LOG IN untuk masuk atau SIGN UP untuk register";
            redirect('registrasi','refresh');
        }

        
        //echo $str_id.'|'.$id;

        //header('Content-Type: application/json');
        //echo json_encode($data_output);
        
        $data = array(
            'output'=> $this->get($str_id,$id),
            'page_title' => 'Profil',
            'page_content' => 'myprofile',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id, 'isUpdate' => false);
        $this->load->view($this->_public_view, $data);
        
     }

     function get($str_id='',$id=''){

        $data_output['success'] = "false";
        $userid = $str_id;
        $myid = $id;
        $myStatus = $this->input->post('myStatus');
        $query_user = $this->db->query("SELECT username, name,password,isPremium,entryDate,lastUpdated,avatar,lastUpdatedAvatar,gender, (SELECT SUM(rateValue)/COUNT(rateValue) FROM rating WHERE providerId = ".$userid." AND rateValue >0) AS rate, (SELECT COUNT(rateValue) FROM rating WHERE providerId = ".$userid." AND rateValue >0) AS voterCount FROM `user` WHERE `id` = '".$userid."'");
        $row_user = $query_user->row();
        if($query_user->num_rows() > 0){
            $data_output['success'] = "true";
            $data_output['id'] = $userid;
            $data_output['username'] = $row_user->username;
            $data_output['password'] = $row_user->password;
            $data_output['name'] = $row_user->name;
            $data_output['isPremium'] = $row_user->isPremium;
            $data_output['entryDate'] = $row_user->entryDate;
            $data_output['lastUpdated'] = $row_user->lastUpdated;
            $data_output['avatar'] = $row_user->avatar;
            $data_output['lastUpdatedAvatar'] = $row_user->lastUpdatedAvatar;
            $data_output['gender'] = $row_user->gender;
            $data_output['rate'] = "".$row_user->rate;
            $data_output['voterCount'] = "".$row_user->voterCount;

            $query_userprofile = $this->db->query("SELECT phoneNumber,bio,address,avatarMotor,lastUpdatedAvatarMotor,motorDesc,motorYear,licenseNumber,deliverCounter,email FROM `userprofile` WHERE `idUser` = '".$userid."'");
            $row_userprofile = $query_userprofile->row();
            $data_output['phoneNumber'] = $row_userprofile->phoneNumber;
            $data_output['bio'] = $row_userprofile->bio;
            $data_output['address'] = $row_userprofile->address;
            $data_output['avatarMotor'] = $row_userprofile->avatarMotor;
            $data_output['lastUpdatedAvatarMotor'] = $row_userprofile->lastUpdatedAvatarMotor;
            $data_output['licenseNumber'] = $row_userprofile->licenseNumber;
            $data_output['motorDesc'] = $row_userprofile->motorDesc;
            $data_output['motorYear'] = $row_userprofile->motorYear;
            $data_output['deliverCounter'] = $row_userprofile->deliverCounter;
            $data_output['email'] = $row_userprofile->email;
        }
        
        $query = $this->db->query("SELECT t.* FROM trip t JOIN `user` u ON u.id=t.userId WHERE departTime >= '".date("Y-m-d H:i:s")."' AND userId = ".$userid." AND t.is_available=1 ORDER BY departTime LIMIT 1");
        if($query->num_rows() < 1){
            $data_output['currentTrip'] = "";
        }else{
            $row = $query->row(); 
            $data_output["currentTrip"][0]["id"] = $row->id;
            $data_output["currentTrip"][0]["status"] = $row->status;
            $data_output["currentTrip"][0]["source_label"] = $row->source_label;
            $data_output["currentTrip"][0]["source_latitude"] = $row->source_latitude;
            $data_output["currentTrip"][0]["source_longitude"] = $row->source_longitude;
            $data_output["currentTrip"][0]["destination_label"] = $row->destination_label;
            $data_output["currentTrip"][0]["destination_latitude"] = $row->destination_latitude;
            $data_output["currentTrip"][0]["destination_longitude"] = $row->destination_longitude;
            $data_output["currentTrip"][0]["via"] = $row->via;
            $data_output["currentTrip"][0]["priceInRupiah"] = $row->priceInRupiah;
            $data_output["currentTrip"][0]["priceInPoint"] = $row->priceInPoint;
            $data_output["currentTrip"][0]["departTime"] = date('d-m-Y H:i:s',strtotime($row->departTime));
            $data_output["currentTrip"][0]["notes"] = $row->notes;
            if($row->status == 'P' && $myid != $userid)             
                $data_output["pickUpStatus"] = $this->getPickupStatus($myid,$userid);
        }
        
        
        $privacy_criteria = " AND t.privacy = 0";
        if($myid === $userid)           $privacy_criteria = "";

        $query = $this->db->query("SELECT COUNT(*) AS historyCount FROM `transaction` t JOIN transactionstatus s ON t.id=s.idTransaction WHERE s.`status` = 'F' AND (userId = ".$userid." OR providerId = ".$userid.")".$privacy_criteria.' ORDER BY t.id DESC LIMIT 3');
        $row = $query->row();
        $historyCount = $row->historyCount;
        $data_output["viewMoreHistory"] = "false";
        $data_output['history'] = "";
        if($historyCount > 0){
            if($historyCount > 3){
                $data_output["viewMoreHistory"] = "true";
            }
            $query = $this->db->query("SELECT DISTINCT t.* FROM `transaction` t JOIN transactionstatus s ON t.id=s.idTransaction WHERE s.`status` = 'F' AND (userId = ".$userid." OR providerId = ".$userid.")".$privacy_criteria.' ORDER BY t.id DESC LIMIT 3');
            $row = $query->row();
            if($query->num_rows() < 1 || $historyCount < 1){
                $data_output['history'] = "";
            }else{
                $count = 0;
                foreach($query->result() as $row){
                    $data_output["history"][$count]["id"] = $row->id;
                    $data_output["history"][$count]["departTime"] = date('d-m-Y H:i:s',strtotime($row->departTime));
                    $data_output["history"][$count]["userId"] = $row->userId;
                    $data_output["history"][$count]["name"] = $this->getNameById($row->userId);
                    $data_output["history"][$count]["avatar"] = $this->getAvatarById($row->userId);
                    $data_output["history"][$count]["lastUpdatedAvatar"] = $this->getLastUpdatedAvatar($row->userId);
                    $data_output["history"][$count]["providerId"] = $row->providerId;
                    $data_output["history"][$count]["providerName"] = $this->getNameById($row->providerId);
                    $data_output["history"][$count]["providerAvatar"] = $this->getAvatarById($row->providerId);
                    $data_output["history"][$count]["providerLastUpdatedAvatar"] = $this->getLastUpdatedAvatar($row->providerId);
                    $data_output["history"][$count]["source_label"] = $row->source_label;
                    $data_output["history"][$count]["source_latitude"] = $row->source_latitude;
                    $data_output["history"][$count]["source_longitude"] = $row->source_longitude;
                    $data_output["history"][$count]["destination_label"] = $row->destination_label;
                    $data_output["history"][$count]["destination_latitude"] = $row->destination_latitude;
                    $data_output["history"][$count]["destination_longitude"] = $row->destination_longitude;
                    $data_output["history"][$count]["paymentMethod"] = $row->paymentMethod;
                    $data_output["history"][$count]["price"] = $row->price;
                    $idTrip = $row->idTrip;
                    $query = $this->db->query("select via,priceInRupiah,priceInPoint from trip where id =".$idTrip);
                    if($query->num_rows() > 0){
                        $row = $query->row();
                        $data_output["history"][$count]["via"] = $row->via;
                    }
                    $count++;
                }
                if($count == 0)             $data_output['history'] = "";
            }
        }
        
        $providerid = $this->input->post('providerId');
        
        $query = $this->db->query("SELECT COUNT(*) AS voterCount FROM rating WHERE providerId = ".$userid);
        $row = $query->row();
        $voterCount = $row->voterCount;
        $data_output['viewMoreComments'] = "false";
        $data_output['comments'] = "";
        if($voterCount > 0){
            if($voterCount > 3){
                $data_output['viewMoreComments'] = "true";
            }
            $count = 0;
            $query = $this->db->query("SELECT reviewerId, u.`name`, u.avatar, u.lastUpdatedAvatar, `comment` FROM comments r JOIN `user` u ON u.id=r.reviewerId WHERE providerId = ".$userid."  AND `comment` IS NOT NULL AND `comment` <> '' LIMIT 3");
            $row = $query->row();
            if($query->num_rows() < 1 || $voterCount < 1){
                $data_output['comments'] = "";
            }else{
                foreach($query->result() as $row){
                    $data_output['comments'][$count]['reviewerId'] = $row->reviewerId;
                    $data_output['comments'][$count]['name'] = $row->name;
                    $data_output['comments'][$count]['avatar'] = $row->avatar;
                    $data_output['comments'][$count]['lastUpdatedAvatar'] = $row->lastUpdatedAvatar;
                    /*$data_output['rating'][$count]['rateValue'] = ''.$row->rateValue;*/
                    $data_output['comments'][$count]['comment'] = $row->comment;
                    $count++;
                }
                if($count == 0)             $data_output['comments'] = "";
            }
        }
        
        $query = $this->db->query("SELECT `comment`, rateValue FROM rating  WHERE providerId = ".$userid." AND reviewerId = ".$myid." LIMIT 1");
        $row = $query->row();
        if($query->num_rows() < 1){
            $data_output['myRating'] = "";
        }else{
            $data_output['myRating'][0]['rateValue'] = ''.$row->rateValue;
            $data_output['myRating'][0]['comment'] = $row->comment;
        }
        return $data_output;
     }

     function update(){
        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        //echo $str_id.' | '.$id;

        $data_output['success'] = "false";
        $error = 0;
        $userid = $id;

        $phoneNumber = $this->input->post('phoneNumber');
        if($error == 0 && $phoneNumber!=NULL){
            $query_phoneNumber = $this->db->query("SELECT COUNT(phoneNumber) AS count FROM `userprofile` WHERE phoneNumber = '".$phoneNumber."' AND `idUser` NOT LIKE ".$userid);
            $row_phoneNumber = $query_phoneNumber->row();
            if($row_phoneNumber->count > 0)             $error = 1;
        }

        $email = $this->input->post('email');
        if($error == 0 && $email!=NULL){
            $query_email = $this->db->query("SELECT COUNT(email) AS count FROM `userprofile` WHERE email = '".$email."' AND `idUser` NOT LIKE ".$userid);
            $row_email = $query_email->row();
            if($row_email->count > 0)               $error = 2;
        }

        if($error == 0){
            $input_data = array(
                'name' => $this->input->post('name'),
                'lastUpdated' => date("Y-m-d H:i:s"),
            );
            if($this->input->post('password')){
                $password = $this->input->post('password');
                if($password != '' || $password == null){
                    $input_data = array(
                        'name' => $this->input->post('name'),
                        'password' => md5($password),
                        'lastUpdated' => date("Y-m-d H:i:s"),
                    );
                }
            } 
            $this->db->where('id', $userid);
            $this->db->update('user', $input_data);
        }

        if($error == 0){
            $input_data = array(
                'phoneNumber' => $this->input->post('phoneNumber'),
                'bio' => $this->input->post('bio'),
                'address' => $this->input->post('address'),
                'licenseNumber' => $this->input->post('licenseNumber'),
                'motorDesc' => $this->input->post('motorDesc'),
                'motorYear' => $this->input->post('motorYear'),
                'email' => $this->input->post('email'),
            );
            $this->db->where('idUser', $userid);
            $this->db->update('userprofile', $input_data);
        }

        if($error == 0){
            $data_output['success'] = "true";
        }else{
            $data_output['error'] = "".$error;
        }
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        // $data = array(
        //     //'output'=> $this->get($str_id,$id),
        //     'page_title' => 'Profil Updated',
        //     'page_content' => 'updated',
        //     'isLogin' => $isLogin, 'user' => $user, 'id' => $id, 'isUpdate' => false);
        // $this->load->view($this->_public_view, $data);
        redirect('home','location');

    }

     function getNameById($userid){
        $query = $this->db->query("SELECT `name` FROM `user`WHERE `id`=".$userid."");
        $row = $query->row();
        return $row->name;
    }
    
    function getAvatarById($userid){
        $query = $this->db->query("SELECT `avatar` FROM `user`WHERE `id`=".$userid."");
        $row = $query->row();
        return $row->avatar;
    }
    
        
    function getLastUpdatedAvatar($userid){
        $query = $this->db->query("SELECT `lastUpdatedAvatar` FROM `user` WHERE `id`=".$userid."");
        $row = $query->row();
        return $row->lastUpdatedAvatar;
    }
    
    function getPickupStatus($myid,$userid){
        $query = $this->db->query("SELECT ts.`status`, ts.`idTransaction` FROM transactionstatus ts JOIN `transaction` t ON t.id=ts.idTransaction WHERE t.userId=".$myid." AND t.providerId=".$userid." ORDER BY ts.`timeStamp` DESC LIMIT 1");
        if($query->num_rows()>0){
            $row = $query->row();
            if($row->status == "F" || $row->status == "C"){
                return 'A';
            } else    {      
             return $row->status;
            }
        }else{
            //echo 'halo';
            return 'A';
        }
    }

    function confirmPremium(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        $data_output['success'] = "false";
        $input_data = array(
            'idUser' => $id,
            'date_time' => date("Y-m-d H:i:s"),
        );
        $this->db->insert('confirm', $input_data);
        if($this->db->affected_rows() > 0)      $data_output['success'] = "true";
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        redirect('home','refresh');
    }

    function confirm(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }
        //echo $str_id.'|'.$id;

        $data = array(
            //'detail' => $this->muser->get_user_trip_detail($str_id),
            'output' => $this->get($str_id,$id),
            'page_title' => 'Konfirmasi Pembayaran',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'confirm');
       $this->load->view($this->_public_view, $data);
    }
    
    function gopremium(){
        $error = 0;
        // $userId = $this->input->post('userId');
        // $username = $this->input->post('username');

        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        $userId = $str_id;
        $username = $user;
        // $password = $this->input->post('password1');
        
        // if($this->checkPassword($username,$this->input->post('password')) == FALSE){
        //     $error = 44;// password salah
        // }
        
        if($error == 0 && $username!=NULL){
            if($this->checkAvailableUsername($username) == TRUE){
                $query_username = $this->db->query("SELECT COUNT(username) AS count FROM `user` WHERE username = '".$username."' AND `id` NOT LIKE ".$userId);
                $row_username = $query_username->row();
                if($row_username->count > 0)                $error = 3;
            }else{
                $error = 3;
            }
        }
        
        $phoneNumber = $this->input->post('phone');
        if($error == 0 && $phoneNumber!=NULL){
            if($this->checkAvailablePhone($phoneNumber) == TRUE){
                $query_phoneNumber = $this->db->query("SELECT COUNT(phoneNumber) AS count FROM `userprofile` WHERE phoneNumber = '".$phoneNumber."' AND `idUser` NOT LIKE ".$userId);
                $row_phoneNumber = $query_phoneNumber->row();
                if($row_phoneNumber->count > 0)             $error = 1;
            }else{
                $error = 1;
            }
        }

        $email = $this->input->post('email1');
        if($error == 0 && $email!=NULL){
            if($this->checkAvailableEmail($email) == TRUE){
                $query_email = $this->db->query("SELECT COUNT(email) AS count FROM `userprofile` WHERE email = '".$email."' AND `idUser` NOT LIKE ".$userId);
                $row_email = $query_email->row();
                if($row_email->count > 0)               $error = 2;
            }else{
                $error = 2;
            }
        }       
        if($error == 0 && $email!=NULL && $phoneNumber!=NULL && $username!=NULL){
            
            // $url = 'http://admin:1234@indobarter.com/api/index.php/api/ojegapi/register';
            // $data = array(
            //     'username' => $this->input->post('username'),
            //     'name' => $this->input->post('name'),
            //     'password1' => $this->input->post('password1'),
            //     'email1' => $this->input->post('email1'),
            //     'address1' => $this->input->post('address1'),
            //     'city' => $this->input->post('city'),
            //     'postal_code' => $this->input->post('postal_code'),
            //     'phone' => $this->input->post('phone'),
            //     'website' => $this->input->post('website'),
            //     'aboutme' => $this->input->post('aboutme'),
            //     'dob' => $this->input->post('dob')
            // );
        
            // $options = array(
            //     'http' => array(
            //         'method'  => 'POST',
            //         'content' => json_encode( $data ),
            //         'header'=>  "Content-Type: application/json\r\n" .
            //         "Accept: application/json\r\n"
            //     )
            // );

            // $context  = stream_context_create( $options );
            // $result = file_get_contents( $url, true, $context );
            // $response = json_decode( $result , true);
            // if(strcmp ($response['status'], 'success') == 0){
                
                $input_data = array(
                    'phoneNumber' => $this->input->post('phone'),
                    'email' => $this->input->post('email1'),
                    'address' => $this->input->post('address1'),
                    'bio' => $this->input->post('aboutme'),
                );
                $this->db->where('idUser', $userId);
                $this->db->update('userprofile', $input_data);
                
                $input_data = array(
                    'username' => $this->input->post('username'),
                    'no_rekening' => $this->input->post('phone'),
                    'password' => $this->input->post('password1'),
                    'lastUpdated' => date("Y-m-d H:i:s"),
                    'isPremium' => 2,
                );
                $this->db->where('id', $userId);
                $this->db->update('user', $input_data);
                echo 'masuk db';
                if($this->db->affected_rows() > 0 ){
                    $data_output['success'] = "true";
                    // header('Content-Type: application/json');
                    // echo json_encode($data_output);
                    redirect('home','refresh');
                }
            // }else{ echo 'lalala';
            //     $data_output['success'] = "false";
            //     $data_output['error'] = "".$error;
            //     header('Content-Type: application/json');
            //     echo json_encode($data_output);
            // }
        
        }else{
            $data_output['success'] = "false";
            $data_output['error'] = "".$error;
            header('Content-Type: application/json');
            echo json_encode($data_output);
        }
        
    }

    function premium(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }
        //echo $str_id.'|'.$id;

        $data = array(
            //'detail' => $this->muser->get_user_trip_detail($str_id),
            'output' => $this->get($str_id,$id),
            'page_title' => 'Go Premium',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'premium');
       $this->load->view($this->_public_view, $data);
    }

    function checkAvailableUsername($username){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/cekusername/username/'.$username;
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status']))         return true;
        else            return false;
    
    }
    
    function checkAvailableEmail($email){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/cekemail/emailid/'.str_replace($email, '@', '/server/');
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status']))         return true;
        else            return false;
    
    }
    
    function checkAvailablePhone($phone){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/ceknorekening/norekening/'.$phone;
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status']))         return true;
        else            return false;
    
    }

    function lupaPassword(){
        $error = 0;
        $data_output['success'] = "false";
        $usernameoremail = $this->input->post('usernameoremail');
        $query_user = $this->db->query("SELECT username,`name`, email FROM `user` u JOIN userprofile p ON u.id=p.idUser WHERE u.username = '".$usernameoremail."' OR p.email = '".$usernameoremail."'");
        if($query_user->num_rows() > 0){
            $result = $query_user->row_array();
            $newPassword = $this->sendNewPassword($result);
            if($newPassword){
                $input_data = array(
                    'password' => md5($newPassword),
                    'lastUpdated' => date("Y-m-d H:i:s"),
                );
                $this->db->where('username', $result['username']);
                $this->db->update('user', $input_data);

                $data_output['success'] = "true";
                redirect('home','refresh');
            }else{
                $error = 2;
                $data = array('page_content' => 'reset_password', 'page_title' =>'Reset Password',
                'error' => 'Maaf, gagal mengirim password baru',
                'isLogin'=>'');
            $this->load->view($this->_public_view, $data);
            }
        }else{
            $error = 1;
            $data = array('page_content' => 'reset_password', 'page_title' =>'Reset Password',
                'error' => 'silakan masukkan alamat email anda yang terdaftar',
                'isLogin'=>'');
            $this->load->view($this->_public_view, $data);
        }
        if($error > 0)          $data_output['error'] = "".$error;
        // header('Content-Type: application/json');
        // echo json_encode($data_output);

    }
    
    function sendNewPassword($user){
        $un = $user['username'];
        $name = $user['name'];
        $email = $user['email'];
        //$password = $this->system_libs->shuffle_char(6);
        $password = random_string('alnum',8);
        
        $this->load->library('email');
        $config['protocol'] = 'sendmail';
        $config['mailpath'] = '/usr/sbin/sendmail';
        $config['charset'] = 'iso-8859-1';
        $config['wordwrap'] = TRUE;

        $this->email->initialize($config);
        $this->email->from('donotreply@o-jex.com', 'O-JEX');
        $this->email->to($email); 
        
        $this->email->subject('Reset O-JEX Password');
        $this->email->message("
            Hello, " .$name .",
            We've received a password request for your account.
            Here are your profile:
            username : " .$un ."
            email : " .$email ."
            password : " .$password 
            ."
            
            O-JEX TEAM
            http://o-jex.com/");    
        
        if($this->email->send())            return $password;
        else            return FALSE;
    }

    function avatar(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data_output['upload_path']        = $upload_path          = "avatar/" ;
        $data_output['destination_thumbs'] = $destination_thumbs   = "avatar/thumb/" ;

        $data_output['large_photo_exists'] = $data_output['thumb_photo_exists'] = $data_output['error'] = NULL ;
        $data_output['thumb_width']        = "128";
        $data_output['thumb_height']       = "128";
        $data_output['img'] = "";
        
        if (!empty($_POST['upload'])) {
            $config['upload_path']  = $upload_path ;
            $config['file_name'] = $id;
            $config['allowed_types']= 'gif|jpg|png|jpeg';
            $config['max_size']     = '2000';
            $config['max_width']    = '2000';
            $config['max_height']   = '2000';
            $config['overwrite'] = TRUE;

            $this->load->library('upload', $config);

            if ($this->upload->do_upload("image")) {
                $data_output['img']     = $this->upload->data();
                //$data_output['large_photo_exists']  = "<img src=\"".base_url() . $upload_path.$data_output['img']['file_name']."\" alt=\"Large Image\"/>";
                $data_output['large_photo_exists']  = "<img src=\"".base_url() . $upload_path.$config['file_name'].$data_output['img']['file_ext']."\" alt=\"Large Image\"/>";
            }
        }
        elseif (!empty($_POST['upload_thumbnail'])) {
            $x1 = $this->input->post('x1',TRUE) ;
            $y1 = $this->input->post('y1',TRUE) ;
            $x2 = $this->input->post('x2',TRUE) ;
            $y2 = $this->input->post('y2',TRUE) ;
            $w  = $this->input->post('w',TRUE) ;
            $h  = $this->input->post('h',TRUE) ;

            $file_name = $this->input->post('file_name',TRUE) ;
            $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
            $file_name_thumb = $id.'t.'.$file_ext;
            
            if ($file_name) {
                $this->image_moo
                    ->load($upload_path . $file_name)
                    ->crop($x1,$y1,$x2,$y2)
                    ->save($destination_thumbs . $file_name_thumb) ;

                if ($this->image_moo->errors) {
                    $data_output['error'] = $this->image_moo->display_errors() ;
                }
                else {
                    $data_output['thumb_photo_exists'] = "<img src=\"".base_url() . $destination_thumbs . $file_name_thumb."\" alt=\"Thumbnail Image\"/>";
                    $data_output['large_photo_exists'] = "<img src=\"".base_url() . $upload_path.$file_name."\" alt=\"Large Image\"/>";

                    $input_data = array(
                        'avatar' =>  $file_name_thumb,
                        'lastUpdatedAvatar' => date("Y-m-d H:i:s"),
                    );

                    $this->db->where('id', $id);
                    $this->db->update('user', $input_data);
                    $data_output['success'] = "true";
                }
            }
        }
        
        //$this->load->view('crop_form',$data) ;

        $data = array(
            'data_output' => $data_output,
            'output' => $this->get($id,$id),
            'page_title' => 'Ubah Avatar',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'form_avatar');
       $this->load->view($this->_public_view, $data);
    }

    function avatarMotor(){
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data_output['upload_path']        = $upload_path          = "motor/" ;
        $data_output['destination_thumbs'] = $destination_thumbs   = "motor/thumb/" ;

        $data_output['large_photo_exists'] = $data_output['thumb_photo_exists'] = $data_output['error'] = NULL ;
        $data_output['thumb_width']        = "128";
        $data_output['thumb_height']       = "128";
        $data_output['img'] = "";
        
        if (!empty($_POST['upload'])) {
            $config['upload_path']  = $upload_path ;
            $config['file_name'] = $id;
            $config['allowed_types']= 'gif|jpg|png|jpeg';
            $config['max_size']     = '2000';
            $config['max_width']    = '2000';
            $config['max_height']   = '2000';
            $config['overwrite'] = TRUE;

            $this->load->library('upload', $config);

            if ($this->upload->do_upload("image")) {
                $data_output['img']     = $this->upload->data();
                //$data_output['large_photo_exists']  = "<img src=\"".base_url() . $upload_path.$data_output['img']['file_name']."\" alt=\"Large Image\"/>";
                $data_output['large_photo_exists']  = "<img src=\"".base_url() . $upload_path.$config['file_name'].$data_output['img']['file_ext']."\" alt=\"Large Image\"/>";
            }
        }
        elseif (!empty($_POST['upload_thumbnail'])) {
            $x1 = $this->input->post('x1',TRUE) ;
            $y1 = $this->input->post('y1',TRUE) ;
            $x2 = $this->input->post('x2',TRUE) ;
            $y2 = $this->input->post('y2',TRUE) ;
            $w  = $this->input->post('w',TRUE) ;
            $h  = $this->input->post('h',TRUE) ;

            $file_name = $this->input->post('file_name',TRUE) ;
            $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
            $file_name_thumb = $id.'t.'.$file_ext;
            
            if ($file_name) {
                $this->image_moo
                    ->load($upload_path . $file_name)
                    ->crop($x1,$y1,$x2,$y2)
                    ->save($destination_thumbs . $file_name_thumb) ;

                if ($this->image_moo->errors) {
                    $data_output['error'] = $this->image_moo->display_errors() ;
                }
                else {
                    $data_output['thumb_photo_exists'] = "<img src=\"".base_url() . $destination_thumbs . $file_name_thumb."\" alt=\"Thumbnail Image\"/>";
                    $data_output['large_photo_exists'] = "<img src=\"".base_url() . $upload_path.$file_name."\" alt=\"Large Image\"/>";

                    $input_data = array(
                        'avatarMotor' => $file_name_thumb,
                        'lastUpdatedAvatarMotor' => date("Y-m-d H:i:s"),
                    );
                    $this->db->where('idUser', $id);
                    $this->db->update('userprofile', $input_data);
                }
            }
        }
        
        //$this->load->view('crop_form',$data) ;

        $data = array(
            'data_output' => $data_output,
            'output' => $this->get($id,$id),
            'page_title' => 'Ubah Avatar',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'form_avatar');
       $this->load->view($this->_public_view, $data);
    }

    function changeAvatar(){
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data_output['success'] = "false";
        $file = 'avatar';
        $userid = $this->input->post('userId');
        $config['upload_path'] = 'avatar/';
        $config['allowed_types'] = '*';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $userid;
        $config['max_size'] = '2048';
        $this->load->library('upload', $config);
        if($this->upload->do_upload($file)) // if upload success
        {
            $result = $this->upload->data();
            foreach($result as $item => $value){
                $filename = $result['file_name'];
                $this->make_thumb($result['file_path'].$filename, $config['upload_path'].'thumb/'.$config['file_name'].'t'.$result['file_ext'], 150, 150);
            }
            $input_data = array(
                'avatar' =>  $config['file_name'].'t'.$result['file_ext'],
                'lastUpdatedAvatar' => date("Y-m-d H:i:s"),
            );
            $this->db->where('id', $userid);
            $this->db->update('user', $input_data);
            $data_output['success'] = "true";
            
        }
        else{
            $data_output['debugfile'] = $this->upload->do_upload($file);
            $data_output['debugid'] = $userid;
        }
        redirect('profil/detail/'.$id); 
         
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
    }

    function changeAvatarMotor(){
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data_output['success'] = "false";
        $file = 'avatarmotor';
        $userid = $this->input->post('userId');
        $config['upload_path'] = 'motor/';
        $config['allowed_types'] = '*';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $userid;
        $config['max_size'] = '2048';
        $this->load->library('upload', $config);
        if($this->upload->do_upload($file)) // if upload success
        {
            $result = $this->upload->data();
            foreach($result as $item => $value){
                $filename = $result['file_name'];
                $this->make_thumb($result['file_path'].$filename, $config['upload_path'].'thumb/'.$config['file_name'].'t'.$result['file_ext'], 150, 150);
            }
            $input_data = array(
                'avatarMotor' => $config['file_name'].'t_thumb'.$result['file_ext'],
                'lastUpdatedAvatarMotor' => date("Y-m-d H:i:s"),
            );
            $this->db->where('idUser', $userid);
            $this->db->update('userprofile', $input_data);
            $data_output['success'] = "true";
        }
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        redirect('profil/detail/'.$id); 
    }
    
    function make_thumb($src, $dest, $desired_width, $desired_height) {
        $source_path = $src;
        $target_path = $dest; 
        $config['image_library'] = 'gd2';
        $config['source_image'] = $source_path;
        $config['new_image'] = $target_path;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = FALSE;
        $config['width']     = $desired_width;
        $config['height']   = $desired_height;

        $this->load->library('image_lib', $config); 

        $this->image_lib->resize();

        /* read the source image */
        //$source_image = imagecreatefromjpeg($src);
        
        //$width = imagesx($source_image);
        //$height = imagesy($source_image);
        
        /* find the "desired height" of this thumbnail, relative to the desired width  */
        //$desired_height = floor($height * ($desired_width / $width));
        
        /* create a new, "virtual" image */
        //thumb($src, 't', $desired_width, $desired_height);
        //$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
        
        /* copy source image at a resized size */
        //imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
        
        /* create the physical thumbnail image to its destination */
        //imagejpeg($virtual_image, $dest);
    }

}

?>
